package com.yiren.manager.ctrl.elder;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.StringUtil;
import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.Favorites;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrBaseServiceCost;
import com.yiren.entity.YrBeHospitalFee;
import com.yiren.entity.YrBedCost;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderFamilyMember;
import com.yiren.entity.YrElderMemContact;
import com.yiren.entity.YrNursingCost;
import com.yiren.entity.YrStaffInfo;
import com.yiren.entity.YrSubjectRoom;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.elder.YrBeHospitalFeeForm;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.elder.YrElderFamilyMemberForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.form.elder.YrElderMemContactForm;
import com.yiren.manager.form.pension.YrBaseServiceCostForm;
import com.yiren.manager.form.pension.YrBedCostForm;
import com.yiren.manager.form.pension.YrNursingCostForm;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.department.YrSubjectRoomService;
import com.yiren.manager.service.iface.elder.YrBeHospitalFeeService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.pension.YrBaseServiceCostService;
import com.yiren.manager.service.iface.pension.YrBedCostService;
import com.yiren.manager.service.iface.pension.YrNursingCostService;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("elder")
@Controller
public class YrElderController extends GenericController<YrElderForm, YrElder> {

	@Autowired
	private YrElderService selfService;

	@Autowired
	private YrStaffInfoService staffInfoService;

	@Autowired
	private YrBeHospitalFeeService beHospitalFeeService;
	
	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;
	
	@Autowired
	private YrSubjectRoomService subjectRoomService;
	
	@Autowired
	private YrNursingCostService nursingCostService;
	
	@Autowired
	private YrBaseServiceCostService baseServiceCostService;
	
	@Autowired
	private YrBedCostService bedCostService;
	
	// 长者资料登记
	@RequestMapping("/saveElderBaseInfo")
	@ResponseBody
	public HTTPResult<YrElder> saveElderBaseInfo(String data) throws SwallowException, MyException,
			InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrElder> result = new HTTPResult<YrElder>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrElderForm elderForm = tool.mapper("elder", YrElderForm.class);
		YrElderFamilyMemberForm familyMemberForm = tool.mapper("elderFamilyMember", YrElderFamilyMemberForm.class);
		YrElderMemContactForm contactForm = tool.mapper("elderMemContacts", YrElderMemContactForm.class);

		if (null == elderForm || null == familyMemberForm || null == contactForm) {
			throwExp("param.error");
		}
		
		String sqlWhere = "name=?1 AND card_id=?2 AND elder_type=?3";
		QueryResult<YrElder> qrElder = selfService.find(YrElder.class, sqlWhere, new Object[]{elderForm.getName(),elderForm.getCardId(),elderForm.getElderType()});
		if(qrElder.getTotalRecord()>0){
			throwExp("该老者已登记过资料，请勿重复登记");
		}
		
		Date now = new Date();
		elderForm.setElderId(UUIDGenerator.getUUID());
		elderForm.setCreateTime(now);
		elderForm.setUpdateTime(now);
		elderForm.setBeHospitalStatus(0);

		familyMemberForm.setElderFamilyMemberId(UUIDGenerator.getUUID());
		familyMemberForm.setElderId(elderForm.getElderId());
		familyMemberForm.setCreateTime(now);
		familyMemberForm.setUpdateTime(now);

		contactForm.setElderMemContactsId(UUIDGenerator.getUUID());
		contactForm.setElderId(elderForm.getElderId());
		contactForm.setCreateTime(now);
		contactForm.setUpdateTime(now);

		verifyElderInfo(elderForm);
		verifyFamilyMember(familyMemberForm);
		verifyContactForm(contactForm);
		
		YrElder elderEntity = ObjectUtils.objectToObject(elderForm, YrElder.class);
		YrElderFamilyMember memberEntity = ObjectUtils.objectToObject(familyMemberForm, YrElderFamilyMember.class);
		YrElderMemContact contactEntity = ObjectUtils.objectToObject(contactForm, YrElderMemContact.class);

		Favorites favorites = new Favorites();
		favorites.putFavorite(YrElder.class, elderEntity);
		favorites.putFavorite(YrElderFamilyMember.class, memberEntity);
		favorites.putFavorite(YrElderMemContact.class, contactEntity);

		selfService.addByFavorites(favorites);
		List<YrElder> formList = new ArrayList<YrElder>();
		formList.add(elderEntity);
		result.setData(formList);

		return result;
	}
	
	private void verifyElderInfo(YrElderForm elderForm) throws MyException{
		if(StringUtil.isEmpty(elderForm.getName())){
			throwExp("老者姓名不能为空");
		}
		if(null==elderForm.getSex()){
			throwExp("请填选老者性别");
		}
		if(null==elderForm.getBirthday()){
			throwExp("老者出生日期(生日)不能为空");
		}
		if(StringUtil.isEmpty(elderForm.getPeoples())){
			throwExp("老者民族信息不能为空");
		}
		if(StringUtil.isEmpty(elderForm.getCardId())){
			throwExp("老者证件号码不能为空");
		}
		if(StringUtil.isEmpty(elderForm.getMaritalStatus())){
			throwExp("老者婚姻状态不能为空");
		}
		if(StringUtil.isEmpty(elderForm.getRegisteredResidence())){
			throwExp("老者户籍不能为空");
		}
	}
	
	private void verifyContactForm(YrElderMemContactForm contactForm) throws MyException{
		if(StringUtil.isEmpty(contactForm.getName())){
			throwExp("紧急联系人姓名不能为空");
		}
		if(null==contactForm.getSex()){
			throwExp("请填选紧急联系人性别");
		}
		if(null==contactForm.getBirthday()){
			throwExp("紧急联系人出生日期(生日)不能为空");
		}
		if(StringUtil.isEmpty(contactForm.getCardId())){
			throwExp("紧急联系人证件号码不能为空");
		}
		if(StringUtil.isEmpty(contactForm.getRelationship())){
			throwExp("紧急联系人关系不能为空");
		}
		if(StringUtil.isEmpty(contactForm.getPhoneNumber())){
			throwExp("紧急联系人手机号码(联系方式)不能为空");
		}
	}
	
	private void verifyFamilyMember(YrElderFamilyMemberForm familyMemberForm) throws MyException{
		if(StringUtil.isEmpty(familyMemberForm.getName())){
			throwExp("家属姓名不能为空");
		}
		if(null==familyMemberForm.getSex()){
			throwExp("请填选家属性别");
		}
		if(null==familyMemberForm.getBirthday()){
			throwExp("家属出生日期(生日)不能为空");
		}
		if(StringUtil.isEmpty(familyMemberForm.getCardId())){
			throwExp("家属证件号码不能为空");
		}
		if(StringUtil.isEmpty(familyMemberForm.getRelationship())){
			throwExp("家属关系不能为空");
		}
		if(StringUtil.isEmpty(familyMemberForm.getPhoneNumber())){
			throwExp("家属手机号码(联系方式)不能为空");
		}
	}

	// 保存实体
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrElderForm> save(String data) throws SwallowException, MyException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
		HTTPResult<YrElderForm> result = new HTTPResult<YrElderForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrElderForm form = tool.mapper("elder", YrElderForm.class);
		if (null == form) {
			throwExp("param.error");
		}
		if (null == form.getElderId() || form.getElderId().isEmpty()) {
			form.setElderId(UUIDGenerator.getUUID());
			form.setCreateTime(new Date());
		}
		form.setUpdateTime(new Date());
		YrElder entity = ObjectUtils.objectToObject(form, YrElder.class);
		selfService.save(entity);

		return result;
	}

	@RequestMapping("findOne")
	@ResponseBody
	public HTTPResult<YrElderForm> findOne(String id) throws Exception {
		HTTPResult<YrElderForm> result = new HTTPResult<YrElderForm>();
		YrElder elder = selfService.findOne(id);

		YrElderForm form = toForm(elder);

		YrStaffInfo staffInfo = staffInfoService.findOne(elder.getCreateId());
		if (null != staffInfo) {
			form.setRecorder(staffInfo.getName());
		}
		List<YrElderForm> formList = new ArrayList<YrElderForm>();
		formList.add(form);

		result.setData(formList);
		return result;
	}

	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrElderForm> find(String searchVal,Integer elderType) throws Exception {
		HTTPResult<YrElderForm> result = new HTTPResult<YrElderForm>();
		String sqlWhere ;
		QueryResult<YrElder> qr;
		if(null!=elderType){
			sqlWhere = "(name=?1 OR card_id=?2) AND elder_type=?3";
			qr = selfService.find(YrElder.class, sqlWhere, new Object[] { searchVal, searchVal,elderType});
		}else {
			sqlWhere = "name=?1 OR card_id=?2";
			qr = selfService.find(YrElder.class, sqlWhere, new Object[] { searchVal, searchVal});
		}
		List<YrElderForm> formList = new ArrayList<YrElderForm>();
		for(YrElder elder : qr.getResultList()){
			YrElderForm form = toForm(elder);
			sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class , sqlWhere, new Object[]{elder.getElderId()});
			if(elderType==1){//如果是院内老人
				if(qrElderBeHospital.getTotalRecord()>0){
					YrElderBeHospitalForm elderBeHospitalForm = ObjectUtils.objectToObject(qrElderBeHospital.getResultList().get(0), YrElderBeHospitalForm.class);
					YrSubjectRoom subjectRoom = subjectRoomService.findOne(elderBeHospitalForm.getSubjectRoomId());
					sqlWhere = "subject_room_id=?1 AND manager_of_subject_room=1";
					QueryResult<YrStaffInfo> qrStaffInfo = staffInfoService.find(YrStaffInfo.class, sqlWhere, new Object[]{subjectRoom.getSubjectRoomId()});
					if(qrStaffInfo.getTotalRecord()>0){
						elderBeHospitalForm.setSubjectRoomManager(qrStaffInfo.getResultList().get(0).getName());
					}
					form.setElderBeHospitalForm(elderBeHospitalForm);
					
					sqlWhere = "be_hospital_id=?1";
					QueryResult<YrBeHospitalFee> qrBeHospitalFee = beHospitalFeeService.find(YrBeHospitalFee.class, sqlWhere, new Object[]{elderBeHospitalForm.getBeHospitalId()}); 
					
					if(qrBeHospitalFee.getTotalRecord()>0){
						YrBeHospitalFeeForm beHospitalFeeForm = ObjectUtils.objectToObject(qrBeHospitalFee.getResultList().get(0), YrBeHospitalFeeForm.class);
						form.setBeHospitalFeeForm(beHospitalFeeForm);
					}
					if(elderBeHospitalForm.getHouseTypeType()==2){//如果是普通户型
						YrBedCost bedCost = bedCostService.findOne(elderBeHospitalForm.getBedCostId());
						if(null!=bedCost){
							YrBedCostForm bedCostForm = ObjectUtils.objectToObject(bedCost, YrBedCostForm.class);
							elderBeHospitalForm.setBedCostForm(bedCostForm);
						}
					}
					YrBaseServiceCost baseServiceCost = baseServiceCostService.findOne(elderBeHospitalForm.getBaseServiceCostId());
					if(null!=baseServiceCost){
						YrBaseServiceCostForm baseServiceCostForm = ObjectUtils.objectToObject(baseServiceCost, YrBaseServiceCostForm.class);
						elderBeHospitalForm.setBaseServiceCostForm(baseServiceCostForm);
					}
					YrNursingCost nursingCost = nursingCostService.findOne(elderBeHospitalForm.getNursingCostId());
					if(null!=nursingCost){
						YrNursingCostForm nursingCostForm = ObjectUtils.objectToObject(nursingCost, YrNursingCostForm.class);
						elderBeHospitalForm.setNursingCostForm(nursingCostForm);
					}
					formList.add(form);
				}
			}else{
				formList.add(form);
			}
		}
		if(elderType==1&&formList.isEmpty()){//如果是院内老人
			throwExp("没有相关老者的入院信息或该老者已出院");
		}

		result.setData(formList);
		return result;
	}

	@RequestMapping("findBaseInfo")
	@ResponseBody
	public HTTPResult<YrElderForm> findBaseInfo(String searchVal,Integer elderType) throws Exception{
		HTTPResult<YrElderForm> result = new HTTPResult<YrElderForm>();
		String sqlWhere ;
		QueryResult<YrElder> qr;
		if(null!=elderType){
			sqlWhere = "(name=?1 OR card_id=?2) AND elder_type=?3";
			qr = selfService.find(YrElder.class, sqlWhere, new Object[] { searchVal, searchVal,elderType});
		}else {
			sqlWhere = "name=?1 OR card_id=?2";
			qr = selfService.find(YrElder.class, sqlWhere, new Object[] { searchVal, searchVal});
		}
		List<YrElderForm> formList = new ArrayList<YrElderForm>();
		for(YrElder elder : qr.getResultList()){
			YrElderForm form = toForm(elder);
			formList.add(form);
		}

		result.setData(formList);
		return result;
	}
	
	@RequestMapping("findDetail")
	@ResponseBody
	public HTTPResult<YrElderForm> findDetail(String elderId) throws Exception {
		HTTPResult<YrElderForm> result = new HTTPResult<YrElderForm>();

		YrElder elder = selfService.findOne(elderId);
		if(null==elder){
			throwExp("查询不到相关老者信息");
		}
		
		YrElderForm elderForm = toForm(elder);
		
		YrStaffInfo staffInfo = staffInfoService.findOne(elderForm.getCreateId());
		if(null!=staffInfo){
			elderForm.setRecorder(staffInfo.getName());
		}
		String sqlWhere = "elder_id=?1";
		QueryResult<YrBeHospitalFee> qrBeHospitalFee = beHospitalFeeService.find(YrBeHospitalFee.class, sqlWhere, new Object[]{elder.getElderId()}); 
		
		if(qrBeHospitalFee.getTotalRecord()>0){
			YrBeHospitalFee beHospitalFee = qrBeHospitalFee.getResultList().get(0);
			elderForm.setIsFinancialCs(beHospitalFee.getIsFinancialCs());
			elderForm.setBankName(beHospitalFee.getBankName());
			elderForm.setContactName(beHospitalFee.getContactName());
			elderForm.setContactPhoneNumer(beHospitalFee.getContactPhoneNumer());
		}
		List<YrElderForm> formList = new ArrayList<YrElderForm>();
		formList.add(elderForm);

		result.setData(formList);
		return result;
	}

	@Override
	public YrElderForm toForm(YrElder e) throws Exception {
		YrElderForm form = ObjectUtils.objectToObject(e, YrElderForm.class);
		return form;
	}

	@Override
	public YrElder toEntity(YrElderForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
